import { apiUrl, reqTimeout, showNetRequest } from '../../config';
import { message, Modal, notification } from 'antd';
import router from 'umi/router';
import tools from './';

const codeMessage = {
  200: '服务器成功返回请求的数据。',
  201: '新建或修改数据成功。',
  202: '一个请求已经进入后台排队（异步任务）。',
  204: '删除数据成功。',
  400: '发出的请求有错误，服务器没有进行新建或修改数据的操作。',
  401: '用户没有权限（令牌、用户名、密码错误）。',
  403: '用户得到授权，但是访问是被禁止的。',
  404: '发出的请求针对的是不存在的记录，服务器没有进行操作。',
  406: '请求的格式不可得。',
  410: '请求的资源被永久删除，且不会再得到的。',
  422: '当创建一个对象时，发生一个验证错误。',
  500: '服务器发生错误，请检查服务器。',
  502: '网关错误。',
  503: '服务不可用，服务器暂时过载或维护。',
  504: '网关超时。',
};

const checkStatus = response => {
  if (response.status >= 400) {
    const errortext = codeMessage[response.status] || response.statusText;
    notification.error({
      message: `请求错误 ${response.status}: ${response.url}`,
      description: errortext,
    });
  }
  return response;
};

function request(
  path,
  para = {},
  second = reqTimeout,
  any = false,
) {
  const url = any ? path : apiUrl() + path;
  const isLogin = path.indexOf('login') >= 0;
	let token = '', userId = 0;

	if (isLogin || any) return requestFunc();
	else {
		token  = tools.funcGetToken();
		userId = tools.funcGetUserId();

		if (token && userId) return requestFunc();
		else router.replace('/user/login');
	}

  function requestFunc() {
    if (!isLogin && !any) {
      // 自动附上访问令牌
      para.token = token;
      para.userId = userId;
    }
    if (showNetRequest) {
      console.log('================================================================');
      console.log('request url', url);
      console.log('request params', para);
    }
    const params = {
      method: 'POST',
      headers: {
        Accept: 'application/json',
        'Content-Type': 'application/json; charset=utf-8',
      },
      body: JSON.stringify(para),
    };

    return Promise.race([
      fetch(url, params),
      new Promise((resolve, reject) => {
        setTimeout(() => reject(new Error('网络请求超时')), second * 1000);
      }),
    ])
      .then(checkStatus)
      .then(response => {
        return response.json();
      })
      .then(response2 => {
        if (showNetRequest) {
          console.log('response', response2);
        }
        if (!any) {
          if (response2) {
            if (!response2.success) {
              if (response2.status === 1) message.error(response2.msg);
              else if (response2.status === 401) {
                Modal.destroyAll();
                Modal.confirm({
                  title: '登录状态异常',
                  content: response2.msg,
                  cancelText: '不',
                  okText: '好',
                  onOk: () => router.replace('/user/login'),
                });
              } else if (response2.status === 402) {
                router.replace('/user/login');
              }
            }
          }
        }
        return response2;
      })
      .catch(err => {
        let description = err.toString();
        if (description.indexOf('Failed to fetch') >= 0) description = '网络连接失败';
        notification.error({ message: url, description });
        return {
          msg: description,
          success: false,
          status: -1,
        };
      });
  }
}

export default request;
